package com.wangjie.simple;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jieshao
 * @date 2022/5/30 15:24
 *
 * 2006. 差的绝对值为 K 的数对数目
 */
public class Test12 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 1};
        int res1 = countKDifference1(arr, 1);
        System.out.println(res1);

        int res2 = countKDifference2(arr, 1);
        System.out.println(res2);
    }

    public static int countKDifference1(int[] nums, int k) {
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (Math.abs(nums[i] - nums[j]) == k) {
                    res++;
                }
            }
        }
        return res;
    }

    public static int countKDifference2(int[] nums, int k) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            res += map.getOrDefault(nums[i] + k, 0) + map.getOrDefault(nums[i] - k, 0);
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        return res;
    }
}